interface Props {
  userId: string;
  width: number;
  height: number;
  [key: string]: any;
}

// 生成确定性随机颜色的函数
const getDeterministicColor = (str: string, index: number) => {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }
  const colors = [
    "#FF6B6B",
    "#4ECDC4",
    "#45B7D1",
    "#FFBE0B",
    "#FB5607",
    "#FF006E",
    "#8338EC",
    "#3A86FF",
    "#38B000",
    "#9EF01A",
    "#FF9E00",
    "#7209B7",
    "#F15BB5",
    "#00BBF9",
    "#00F5D4",
    "#FEE440",
    "#9B5DE5",
    "#00F5D4",
    "#FEE440",
    "#9B5DE5",
  ];
  return colors[Math.abs(hash + index) % colors.length];
};

// 生成确定性渐变色的函数
const getDeterministicGradient = (str: string) => {
  let hash = 0;
  for (let i = 0; i < str.length; i++) {
    hash = str.charCodeAt(i) + ((hash << 5) - hash);
  }

  const gradients = [
    `linear-gradient(45deg, ${getDeterministicColor(str, 0)}, ${getDeterministicColor(str, 3)})`,
    `linear-gradient(135deg, ${getDeterministicColor(str, 1)}, ${getDeterministicColor(str, 4)})`,
    `linear-gradient(90deg, ${getDeterministicColor(str, 2)}, ${getDeterministicColor(str, 5)})`,
    `linear-gradient(45deg, ${getDeterministicColor(str, 1)}, ${getDeterministicColor(str, 4)})`,
    `linear-gradient(135deg, ${getDeterministicColor(str, 2)}, ${getDeterministicColor(str, 5)})`,
  ];

  return gradients[Math.abs(hash) % gradients.length];
};

export default function TextAvatar({ userId, width, height, ...props }: Props) {
  // 获取前两个英文字符或第一个中文字符
  let text = "";
  if (/^[a-zA-Z]/.test(userId)) {
    // 如果以英文字母开头，取前两个字符
    text = userId.substring(0, 2);
  } else {
    // 否则取第一个字符（可能是中文或其他字符）
    text = userId.substring(0, 1);
  }

  // 生成基于用户名的确定性渐变背景
  const background = getDeterministicGradient(userId);
  const textColor = "#FFFFFF"; // 使用白色文字确保可读性

  const avatarStyle = {
    width: width + "px",
    height: height + "px",
    borderRadius: "50%",
    background,
    color: textColor,
    display: "flex",
    alignItems: "center",
    justifyContent: "center",
    fontSize: width / 2 + "px",
    fontWeight: "bold",
    textTransform: "uppercase" as "uppercase",
    boxShadow: "0 0 8px rgba(0,0,0,0.3)", // 添加轻微阴影增强光泽效果
  };

  return (
    <div style={avatarStyle} {...props}>
      {text}
    </div>
  );
}
